import { useEffect, useReducer } from 'react'

import TodoAdd from './components/TodoAdd'
import TodoFooter from './components/TodoFooter'
import MainSection from './components/MainSection'
import TodoContext from './TodoContext'
import { reducer, initialState } from './reducer'
// 导入todos样式
import './App.css'

const App = () => {
  const [todos, todosDispatch] = useReducer(reducer, initialState)
  // const [todos, setTodos] = useState(initialState)
  // 添加任务
  const onAdd = (text: string) => {
    todosDispatch({ type: 'add', payload: text })
  }
  // 切换状态
  const onToggle = (id: number) => {
    todosDispatch({ type: 'toggle', payload: id })
  }
  // 删除任务
  const onDelete = (id: number) => {
    todosDispatch({ type: 'delete', payload: id })
  }
  // 本地化  1.读取本地数据 2.数据改变时存储数据
  // 读取localhost中的数据
  useEffect(() => {
    const res = localStorage.getItem('todos')
    if (res) {
      const resTodos = JSON.parse(res)
      todosDispatch({ type: 'loadData', payload: resTodos })
    }
  }, [])
  // 保存最新的数据到localStorage
  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos))
  }, [todos])
  return (
    <TodoContext.Provider
      value={{
        todos: todos,
        onDeleteTodo: onDelete,
        onToggleTodo: onToggle
      }}
    >
      <section className='todoapp'>
        {/* 添加任务 */}
        <TodoAdd onAddTodo={onAdd} />
        {/* 改造的地方 */}
        <MainSection></MainSection>
        {/* footer 组件 */}
        <TodoFooter />
      </section>
    </TodoContext.Provider>
  )
}

export default App
